#include <stdlib.h>
#include <string.h>
#include "order.h"
#include "file.h"

static Item *order = NULL;

Item *order_parse(const char *cstr)
{
    code = strtok(cstr, " ");
    num = strtok(NULL, " ");
    Item *p = malloc(sizeof(Item));
    *(num - 1) = '\0';
    *p = (Item) {
        .code = code, .num_units = atoi(num),
    };
    return p;
}

void order_read(const char *fpath)
{
    FILE *f = file_open(fpath, "r");
    char *line;
    while(1)
    {
        line = line_read(f);
        if(!line)
            break;
        Item *p = order_parse(line);
        order_add(p);
    }
    free(line);
    fclose(f);
}

void order_add(Item *item)
{
    item->next = NULL;
    if(!order)
    {
        order = item;
        return;
    }
    Item *p = order;
    for(; p->next; p = p->next);
    p->next = item;
}

void order_save(const char *fpath)
{
    FILE *f = file_open(fpath, "wa");
    for(Item *p = order; p; p = p->next)
        fprintf(f, "%s %lu", p->code, p->num_units);
}

void order_free()
{
    for(Item *p = order; p->next; p = q)
    {
        Item *q = p->next;
        free(p);
    }
}
